package edu.ccut.saturn.component.impl.sql;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import edu.ccut.saturn.component.ISaturnDataSqlInfo;
import edu.ccut.saturn.component.ISaturnDataSqlItemInfo;
import edu.ccut.saturn.component.loader.data.SqlLoader;
import edu.ccut.saturn.component.xml.ISaturnElement;
import edu.ccut.saturn.component.xml.SaturnElement;

public class SaturnDataSqlInfo implements ISaturnDataSqlInfo {

	private String id;

	private String description;

	private List<ISaturnDataSqlItemInfo> sqlItemInfos;

	public SaturnDataSqlInfo(String id, String description) {
		this.id = id;
		this.description = description;
		this.sqlItemInfos = new ArrayList<ISaturnDataSqlItemInfo>();
	}

	public String getDescription() {
		return this.description;
	}

	public String getKey() {
		return this.id;
	}

	public String getSql(Map<String, Object> param) throws Exception {
		StringBuffer sqlBuffer = new StringBuffer();

		if (this.sqlItemInfos.size() > 0) {

			for (ISaturnDataSqlItemInfo sqlItemInfo : sqlItemInfos) {
				sqlBuffer.append(sqlItemInfo.getSubSql(param));
			}
		}
		return sqlBuffer.toString();
	}

	public List<ISaturnDataSqlItemInfo> getSaturnDataSqlItemInfos() {
		return this.sqlItemInfos;
	}

	public void setSqlItemInfos(List<ISaturnDataSqlItemInfo> sqlItemInfos) {
		this.sqlItemInfos = sqlItemInfos;
	}

	public ISaturnElement toSaturnElement() {
		ISaturnElement sqlElement = new SaturnElement(SqlLoader.NODE_KEY_SQL);
		sqlElement.addAttribute(SqlLoader.NODE_KEY_ID, this.id);
		ISaturnElement descriptionElement = new SaturnElement(
				SqlLoader.NODE_KEY_DESCRIPTION, this.description);

		sqlElement.addSubElement(descriptionElement);

		if (this.sqlItemInfos != null && this.sqlItemInfos.size() > 0) {

			for (ISaturnDataSqlItemInfo sqlItemInfo : this.sqlItemInfos) {
				sqlElement.addSubElement(sqlItemInfo.toSaturnElement());
			}
		}
		return sqlElement;
	}

	public String toXmlStr() {
		return toSaturnElement().getXMLStr();
	}
}
